public with sharing class AddSaloonAndPocketSessionAttendance {

  
      public string orderby{get;set;}//'dept__c,class1__c,class2__c,class3__c';
      public boolean showbutton{get;set;}
/*      public boolean sortbydept{get;set;}
      public boolean sortbyhospital{get;set;}
      public boolean sortbytitle{get;set;}
      public boolean sortbyclass1{get;set;}
      public boolean sortbyclass2{get;set;}
      public boolean sortbyclass3{get;set;} */
      public boolean showcheck{get;set;}
      public boolean showmessage{get;set;}
      public boolean showattend{get;set;}
      public string isattended{get;set;}
      
     public String idStr{
        get{ 
            boolean nothing1 = false;

            return System.currentPageReference().getParameters().get('id');
            }
            set;
      }
      public List<SelectOption> options  
    {
        get
        {
            if(options == null)
                options = new List<SelectOption>();
            else
                options.clear();
            boolean nothing11 = false;    
            options.add(new SelectOption('dept__c','部门'));
            options.add(new SelectOption('admintitle__c','行政人员头衔'));
            options.add(new SelectOption('hospital__c,dept__c','医院'));
            options.add(new SelectOption('class1__c','级别1'));
            options.add(new SelectOption('class2__c','级别2'));
            options.add(new SelectOption('class3__c','级别3'));
            return options ;
        }
        set;
    }
  /*    public string order{get{ 
       system.assert(false,sortbydept);
       if(sortbydept){
       
        orderby='dept__c';
       }
       return orderby;
       }
      set;
      }*/
      
      
/*          public string sortbydept{get
     {
         if(dept.selected){
             orderby+='dept__c';
         }
     }
     set;}
     
     public string sortbytitle{get
          {
         if(title.selected()){
             orderby+='HCPadministrativetitle__c';
         }
     }
     set;}
     
     public string sortbyclass1{get
               {
         if(class1.selected()){
             orderby+='class1__c';
         }
     }
     set;}
     public string sortbyclass2{get
               {
         if(class2.selected()){
             orderby+='class2__c';
         }
     }
     set;}
     public string sortbyclass3{get
               {
         if(class3.selected()){
             orderby+='class3__c';
         }
     }
     set;}
     public string sortbyhospital{get
               {
         if(hospital.selected()){
             orderby+='Hospital2__c';
         }
     }
     set;}*/
     public String searchName{get;set;}
     public string str{get;set;}
     public string msg{get;set;}

            
    public List<HCPEntry> hcpUser{get;set;}
    public List<NationalAttendee__c> selectedCategories {   
         get {

                boolean nothing3 = false;
                boolean nothing4 = false;
                boolean nothing5 = false;
                boolean nothing6 = false;
                boolean nothing7 = false;
                boolean nothing8 = false;
                boolean nothing9 = false;      
                  if (selectedCategories == null) 
                   selectedCategories = new List<NationalAttendee__c>();        
                   return selectedCategories;     
            }    
                   set;   
     }   
      public NationalAttendee__c searchAtt{get;set;}          
      

            List<recordtype> saloonIdl = [select id from recordtype where sobjecttype=:'HCPEducation__c' and name=:'学术沙龙']; //012O00000008UfL
            List<recordtype> pocketIdl = [select id from recordtype where sobjecttype=:'HCPEducation__c' and name=:'科内会'];   //012O00000008UfG          
            
            recordtype saloonId = saloonIdl.get(0);
            recordtype pocketId = pocketIdl.get(0);
            
            recordtype saloonId1 = saloonIdl.get(0);
            recordtype pocketId1 = pocketIdl.get(0);
            recordtype saloonId2 = saloonIdl.get(0);
            recordtype pocketId2 = pocketIdl.get(0);
            recordtype saloonId3 = saloonIdl.get(0);
            recordtype pocketId3 = pocketIdl.get(0);
            recordtype saloonId4 = saloonIdl.get(0);
            recordtype pocketId4 = pocketIdl.get(0);
            
            
            List<recordtype> nsaloonIdl = [select id from recordtype where sobjecttype=:'NationalAttendee__c' and name=:'学术沙龙']; //012O00000008Ug4
            List<recordtype> npocketIdl  = [select id from recordtype where sobjecttype=:'NationalAttendee__c' and name=:'科内会']; //012O00000008Ug9           
          
            recordtype nsaloonId= nsaloonIdl.get(0);
            recordtype npocketId= npocketIdl.get(0);
            
            recordtype nsaloonId1 = nsaloonIdl.get(0);
            recordtype npocketId1 = npocketIdl.get(0);
            recordtype nsaloonId2 = nsaloonIdl.get(0);
            recordtype npocketId2 = npocketIdl.get(0);
            recordtype nsaloonId3 = nsaloonIdl.get(0);
            recordtype npocketId3 = npocketIdl.get(0);
            recordtype nsaloonId4 = nsaloonIdl.get(0);
            recordtype npocketId4 = npocketIdl.get(0);            
          

    public PageReference SearchUser()
    {

       
  //  system.assert(false,orderby);
        hcpeducation__c hcpedul=[select recordtypeid,id,date__c from hcpeducation__c where id=:idstr];
        list<id> idl=new list<id>();
        list<joinpeople__c> jpl=new  list<joinpeople__c>();
        Boolean b=true;
        jpl=[select User__c from JoinPeople__c where NationalHCPEducation__c=:idStr];
        for(joinpeople__c jp:jpl){
            idl.add(jp.user__c);
        }
        for(id id:idl){
            if(userinfo.getuserid()==id){
                b=false;
            }
        }
        if(b && hcpedul.recordtypeid==saloonIdl[0].id ){ 
          msg='您不在参与者名单中，请联系活动组织者进行确认';
          showmessage=true;
          return null;
        }
     
       id uid=userinfo.getuserid();
       string dateValue=null;
       dateValue=hcpedul.date__c.year()+'';
       if(string.valueof(hcpedul.date__c.month()).length()==1){
           datevalue+='-0'+hcpedul.date__c.month();
       }else{
           datevalue+='-'+hcpedul.date__c.month();
       }
       if(string.valueof(hcpedul.date__c.day()).length()==1){
           datevalue+='-0'+hcpedul.date__c.day();
       }else{
           datevalue+='-'+hcpedul.date__c.day();
       }
     //  system.assert(false,datevalue);
           String sql='select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where name like \'%'+searchName+'%\' and (Active__c=true or (effectivedate__c <='+datevalue+'  and approvaltype__c != \'删除医护人员\' ) ) and hospital__r.ownerid = \''+userinfo.getuserid()+'\'  and id not in(select HCP__c from NationalAttendee__c where HCPEducation__c=\''+idStr+'\' )';
       
       if(searchAtt.Hospital__c!=null)
       {
           sql+=' and Hospital__c=\''+searchAtt.Hospital__c+'\'';
       }
       if(orderby!=null){
       sql+=' order by '+orderby;//Dept__c';
       }
       if(hcpUser==null)
       {
              hcpUser=new List<HCPEntry>();
       }
       else
       {
           hcpUser.clear();
       }

       if(idStr != null){
       hcpeducation__c hcpdate=[select id,date__c,recordtypeid from hcpeducation__c where id=:idstr];
       for(HCP__c nasql:Database.query('select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where hospital__r.ownerid = \''+userinfo.getuserid()+'\' and id  in(select HCP__c from NationalAttendee__c where inplan__c=true and isattended__c=true and HCPEducation__c=\''+idStr+'\' )')){
           HCPEntry naen=new HCPEntry(nasql);
           hcpUser.add(naen);
           for(HCPEntry h:hcpuser){
           if(hcpdate.date__c<=date.today()&&hcpdate.recordtypeid==pocketIdl[0].id){
               h.showcheck=true;
           }
           h.isattended='已出席';
           h.checked=true;}
           }
        for(HCP__c nasql:Database.query('select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where hospital__r.ownerid = \''+userinfo.getuserid()+'\' and id  in(select HCP__c from NationalAttendee__c where inplan__c=true and isattended__c=false and HCPEducation__c=\''+idStr+'\' )')){
           HCPEntry naen=new HCPEntry(nasql);
           hcpUser.add(naen);
           for(HCPEntry h:hcpuser){
           if(hcpdate.date__c<=date.today()&&hcpdate.recordtypeid==pocketIdl[0].id){
               h.showcheck=true;
           }
           h.checked=true;}
           }
       for(HCP__c nasql:Database.query('select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where hospital__r.ownerid = \''+userinfo.getuserid()+'\'  and id  in(select HCP__c from NationalAttendee__c where inplan__c=false and isattended__c=true and HCPEducation__c=\''+idStr+'\' )')){
           HCPEntry naen=new HCPEntry(nasql);
           hcpUser.add(naen);
           for(HCPEntry h:hcpuser){
           h.isattended='已出席';
           h.checked=true;}}
       for(HCP__c nasql:Database.query('select id,name,Hospital__c,Dept__c,admintitle__c,class1__c,class2__c,class3__c from HCP__c where hospital__r.ownerid = \''+userinfo.getuserid()+'\'  and id  in(select HCP__c from NationalAttendee__c where inplan__c=false and isattended__c=false and HCPEducation__c=\''+idStr+'\' )')){
           HCPEntry naen=new HCPEntry(nasql);
           hcpUser.add(naen);
           for(HCPEntry h:hcpuser){
           h.checked=true;}}
       for(HCP__c u:Database.query(sql)){
           HCPEntry entry=new HCPEntry(u);
           hcpUser.add(entry);           
       
         }
       } 
       return null;
    }
    
    public AddSaloonAndPocketSessionAttendance()
    {
        //idstr=System.currentPageReference().getParameters().get('id'); 
        hcpUser=new list<HCPEntry>();
        searchName='';
        selectedCategories=new List<NationalAttendee__c>();
        searchAtt=new NationalAttendee__c();
        list<hcpeducation__c> hcpautol=[select id,recordtypeid,Hospital__c,date__c from hcpeducation__c where id=:idstr];   
        if(hcpautol.size()>0&&pocketidl.size()>0){
        if(hcpautol[0].recordtypeid==pocketidl[0].id){
            showattend=true;
        }
        }
        orderby='hospital__c,dept__c';
        if(hcpautol.size()>0){
     
        searchAtt.hospital__c=hcpautol[0].hospital__c;
        SearchUser();

         if(hcpautol[0].recordtypeid==saloonIdl[0].id){    
                Date Dtoday = Date.today();
                if(Dtoday < hcpautol[0].date__c) 
                {
                    showbutton=true;
                }              
                else if(Dtoday > hcpautol[0].date__c.addmonths(1).toStartOfMonth()+5 )         // date.valueof(2010-13-1)//hcpautol[0].date__c.year()+'-'+ nextmonth  + '-'+6)-1)
                {
                   //  showbutton=true;
                }
                }
            if(hcpautol[0].recordtypeid==pocketidl[0].id){    
            showattend=true;   
          //       if(date.today()>hcpautol[0].date__c+1){
           // showbutton=true;
         //      }
               
                 }
                
           }
       
    }

public PageReference submitUser()
    { 
    id uid=userinfo.getuserid();
      if(hcpUser==null){
        pageReference pr = new pageReference('/'+ idStr);           
        pr.setredirect(true);      
        return pr;
     
        }else {
        List<HCPEducation__c> hcpclean=new List<HCPEducation__c>();
        hcpclean=[select TotalNumberoftargetHCP__c,LocalActivityAttends__c,totalarrived__c,date__c,recordtypeid from HCPEducation__c where id=:idStr];
        if(hcpclean[0].totalarrived__c==null&&hcpclean[0].date__c<=date.today()){
          hcpclean[0].totalarrived__c=0;
         }
        if(hcpclean.size()>0){
          hcpclean[0].LocalActivityAttends__c=0;
          hcpclean[0].totalnumberoftargetHCP__c=0;
          update hcpclean[0];
        }
        if(selectedCategories!=null)
           selectedCategories.clear();
           List<NationalAttendee__c> nal=new List<NationalAttendee__c>();
           if(hcpclean[0].date__c<=date.today()&&hcpclean[0].recordtypeid==pocketIdl[0].id){
           nal=[select id from NationalAttendee__c where ownerid=:uid and HCPEducation__r.Id=:idStr and inplan__c=:false];    
           }else{
           nal=[select id from NationalAttendee__c where ownerid=:uid and HCPEducation__r.Id=:idStr];   
           }        
           if (nal.size()>0){            
             delete nal;            
           }
            
        for(HCPEntry en:hcpUser)
        {//system.assert(false,hcpuser);
            if(en.checked&&(!(en.showcheck)))
            {
            
             HCPEducation__c hcpl=[select RecordTypeId,date__c from HCPEducation__c where id=:idStr];
            
              if(hcpl.RecordTypeId==saloonId.Id){
         /*       HCPEducation__c cnl = [Select date__c,Id,Name From HCPEducation__c Where id =: idStr ];
                */
               NationalAttendee__c mem=new NationalAttendee__c();         
               mem.HCPEducation__c = idStr;
               mem.HCP__c=en.hcpList.id;
               mem.RecordTypeid=nsaloonId.Id;
               mem.IsAttended__c=true;
               mem.inplan__c=true;
               selectedCategories.add(mem);
                 }
              else if(hcpl.RecordTypeId== pocketId.Id ){
              
               NationalAttendee__c mem=new NationalAttendee__c();         
               mem.HCPEducation__c = idStr;
               mem.HCP__c=en.hcpList.id;
               mem.RecordTypeid=npocketId.Id  ;
               if(date.today()<hcpl.date__c||en.showcheck==true){
                   mem.inplan__c=true;
               }
               if(en.isattended=='已出席' || (date.today()>=hcpl.date__c && en.showcheck != true)){
                   mem.isattended__c=true;
               }
               selectedCategories.add(mem);
                 }
                
               
            }
        }
        
           insert selectedCategories;
           
           list<hcpeducation__c>  hcpl=[select TotalNumberoftargetHCP__c,id,totalarrived__c,date__c from HCPEducation__c where id=:idStr and recordtypeid=:pocketid.id];
           list<nationalattendee__c> nall=[select id,IsAttended__c from NationalAttendee__c where inplan__c=:true and HCPEducation__r.id=:idstr];
           
           if(hcpl.size()>0){
           HCPEducation__c hcp=hcpl[0];
           if(nall.size()>0){
           Integer i=nall.size();
           hcp.TotalNumberoftargetHCP__c=i;
           }
           List<NationalAttendee__c> attl=[select IsAttended__c from NationalAttendee__c where IsAttended__c=:true and HCPEducation__r.id=:hcp.id];
                   if(hcp.totalarrived__c==null&&hcp.date__c<=date.today()){
                       hcp.totalarrived__c=0;
                       update hcp;
                   }
           //        system.assert(false,attl.size());
                   hcp.LocalActivityAttends__c=attl.size();
                   
             update hcp;  
        }
        }
        string callplanid =idStr;    
        pageReference pr = new pageReference('/'+ idStr);           
        pr.setredirect(true);      
        return pr;
      }
    

    static testMethod void AddSaloonAndPocketSessionAttendanceTest()
    {               
        HCPEducation__c nhcpe = new HCPEducation__c();
        nhcpe.Name = 'a';
        nhcpe.date__c = date.Today().addDays(6);
        nhcpe.place__c = 'a';
        insert nhcpe;       

        Profile p  = [select id from profile where name =: 'System Administrator' or name =: '系统管理员'];
        UserRole roleSH = [select id from UserRole where name =: 'SOC1 GZ ASM/DSM-M1' limit 1];      
        
        User u1 = new User (alias = 'standt', email = 'shuaicao@isoftstone.com', emailencodingkey='UTF-8',
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='standarduser@testorg1.com',FunctionDepartment__c = 'Medical Sales');
        insert u1;
        
        User u2 = new User (alias = 'stndt', email = 'shuaicaadfo@isoftstone.com', emailencodingkey='UTF-8',
                lastname = 'Testing', languagelocalekey = 'en_US', localesidkey='en_US', Title__c = 'Sales Rep',profileid = p.id, 
                timezonesidkey = 'America/Los_Angeles', username='sarduser@testorg1.com',FunctionDepartment__c = 'Medical Sales');
        insert u2;
     
        NationalAttendee__c nat = new NationalAttendee__c();
        HCPEducation__c hcpe = new HCPEducation__c();
        hcpe.date__c = date.Today() + 10;
        List<recordtype>  saloonIdl = [select id from recordtype where  name=:'学术沙龙'];
        recordtype saloonId = saloonIdl.get(0);
        hcpe.RecordTypeId = saloonId.Id;
        hcpe.place__c = 'place';
        hcpe.Venuetype__c = '本市其它';
        hcpe.Messaging__c = 'Pastor-高水平DHA令宝宝拥有真“智”卓“健”（2010年3月至8月）';
        hcpe.organizer__c = '医院';
        insert hcpe;      
        
        Hospital__c hos = new Hospital__c();
        hos.Name = 'aaaaaaaa';
        hos.Nickname__c = 'aaaaaaaaaaa';
        insert hos;
        
        HCP__c hcp= new HCP__c();
        hcp.class1__c = '全国学术带头人(NKOL)';
        hcp.Hospital__c = hos.Id;
        insert hcp;             
        
        nat.Hospital__c = hos.Id;
        nat.HCPEducation__c = hcpe.Id;
        nat.HCP__c = hcp.Id; 
        insert nat;
       
      System.runAs(u1){     
        JoinPeople__c jp = new JoinPeople__c ();
        jp.NationalHCPEducation__c = hcpe.Id;
        jp.User__c = u2.Id;
        insert jp;    
        
        AddSaloonAndPocketSessionAttendance tstt = new AddSaloonAndPocketSessionAttendance();     
        test.setCurrentPageReference(Page.SearchAttendanceUser);
        System.currentPageReference().getParameters().put('id', hcpe.Id);       
        
        tstt .searchAtt = nat;   
           
        HCPEntry hcpen2 = new HCPEntry(hcp);
        
        tstt .hcpUser = new List<HCPEntry>();
        tstt .hcpUser.add(hcpen2);       
                   
        }

        AddSaloonAndPocketSessionAttendance tsst = new AddSaloonAndPocketSessionAttendance();     
        test.setCurrentPageReference(Page.SearchAttendanceUser);
        System.currentPageReference().getParameters().put('id', hcpe.Id);       
        System.assert(tsst.options != null);
        tsst.selectedCategories = null;
        System.assert(tsst.options != null);
        System.assert(tsst.selectedCategories != null);
        tsst.idstr = hcpe.id;
        tsst.searchAtt = nat;   
        HCPEntry hcpen1 = new HCPEntry(hcp);
        
        tsst.hcpUser = new List<HCPEntry>();
        tsst.hcpUser.add(hcpen1);
        tsst.SearchUser();
                    

      System.runAs(u2){         
        AddSaloonAndPocketSessionAttendance tst = new AddSaloonAndPocketSessionAttendance();     
        test.setCurrentPageReference(Page.SearchAttendanceUser);
        System.currentPageReference().getParameters().put('id', hcpe.Id);       
        
        tst.idstr = hcpe.id;
        tst.searchAtt = nat;   
           
        HCPEntry hcpen = new HCPEntry(hcp);
        
        tst.hcpUser = new List<HCPEntry>();
        tst.hcpUser.add(hcpen);
        tst.SearchUser();        
        tst.submitUser();
        tst.SearchUser(); 
        System.assert(tst.options != null);
        
        tst.hcpUser = null;
        tst.submitUser();
        
        }
    
    }
}